package com.example.bootDemo.config;

import com.example.bootDemo.entity.Permissions;
import com.example.bootDemo.entity.Role;
import com.example.bootDemo.entity.User;
import com.example.bootDemo.service.imp.LoginServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @description: 创建自定义Realm用于查询用户的角色和权限信息并保存到权限管理器
 * @author: zys
 * @create: 2021-04-09 16:53
 **/
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private LoginServiceImpl loginService;

    /**
     * 聚合授权信息
     * 当我们使用 AuthorizingRealm 时，如果身份验证成功，在进行授权时就通过doGetAuthorizationInfo
     * 方法获取角色/权限信息用于授权验证。Shiro 提供了一个实现 SimpleAuthorizationInfo，大多数时候使用这个即可。
     *
     * @param principals
     * @return AuthorizationInfo
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录名信息
        String name = (String) principals.getPrimaryPrincipal();
        //根据用户名查询用户信息
        User user = loginService.getUserByName(name);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //post请求先认证然后到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        //获取登录名信息
        String name = token.getPrincipal().toString();
        //根据用户名查询用户信息
        User user = loginService.getUserByName(name);
        if (user == null) {
            //需要返回对应异常信息
            return null;
        } else {
            //验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword(), getName());
            return simpleAuthenticationInfo;
        }
    }
}
